﻿using System;
using System.Collections.Generic;
using System.Text;
using Xeml.Document;
using Mpi.Common;

namespace Xeml.Document
{
    public static class ValueParser
    {
        public static ValueBase Parse(string valSyntxStr, TimeSpan ts)
        {
            if (ValueParser.IsValidCycleStr(valSyntxStr))
            {
                Cycle c = new Cycle();
                c.Time = ts;
                string timingpart;
                string valpart;
                string[] parts = valSyntxStr.Split(';');
                timingpart = parts[0];
                valpart = parts[1];
                string[] timings = timingpart.Split('/');
                string[] vals = valpart.Split('/');
                for (int i = 0; i < timings.Length; i++)
                {
                    DynamicValue v = new DynamicValue();
                    v.Time = TimeSpanExtension.Parse(timings[i], TimeSpanParseOption.DoubleIsHour);
                    v.Val = vals[i];
                    c.Values.Add(v);
                }
                return c;
            }
            else
            {
                DynamicValue v = new DynamicValue();
                v.Time = ts;
                v.Val = valSyntxStr;
                return v;
            }

        }

        public static bool IsValidCycleStr(string valSyntxStr)
        {
            if (!valSyntxStr.Contains(";"))
                return false;
            {
                string timingpart;
                string valpart;
                string[] parts = valSyntxStr.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length != 2)
                    return false;
                else
                {
                    timingpart = parts[0];
                    valpart = parts[1];
                    string[] timings = timingpart.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    string[] vals = valpart.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    if (timings.Length != vals.Length || timings.Length < 2)
                        return false;
                    else
                    {
                        foreach (string t in timings)
                        {
                            if (TimeSpanExtension.Evaluate(t, TimeSpanParseOption.DoubleIsHour) == TimeSpanSyntax.Invalid)
                                return false;
                        }

                    }
                }
            }
            return true;
        }
    }
}
